package com.huanqiu.mylib.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 实现了 jsbridge 的 WebView
 */
public class CommonWebView extends WebView {

    private static final String JAVASCRIPT_INTERFACE = "jsbridge";

    private final WebViewBridge webViewBridge = new WebViewBridge();
    private MessageHandler messageHandler;

    public CommonWebView(@NonNull Context context) {
        super(context);
        init();
    }

    public CommonWebView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CommonWebView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void init() {
        WebSettings webSettings = getSettings();
        webSettings.setJavaScriptEnabled(true);

        addJavascriptInterface(webViewBridge, JAVASCRIPT_INTERFACE);

        setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                // 不跳到浏览器
                view.loadUrl(request.getUrl().toString());
                return true;
            }
        });

        setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage message) {
                Log.d("webview-js", "[" + message.messageLevel() + "] " + message.message()
                        + " (" + message.sourceId()
                        + " : line " + message.lineNumber()
                        + ")");
                return true;
            }
        });
    }

    // native -> web
    public void postMessage(String str) {
        this.evaluateJavascript("window.jsbridge.onMessage('" + str + "')", null);
    }

    public void setMessageHandler(MessageHandler messageHandler) {
        this.messageHandler = messageHandler;
    }

    public interface MessageHandler {
        void onMessage(String message);
    }

    private class WebViewBridge {
        // web -> native
        @JavascriptInterface
        public void postMessage(String message) {
            if (CommonWebView.this.messageHandler == null) return;
            CommonWebView.this.post(() -> {
                CommonWebView.this.messageHandler.onMessage(message);
            });
        }
    }

}
